package com.gxl.util;

import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MyBatisUtil {
	private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();
	private static SqlSessionFactory sqlSessionFactory = null;
	private static SqlSession sqlSession = null;
	static{
		try {
			InputStream resourceAsStream = Resources.getResourceAsStream("mybatis.xml");
			sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static SqlSession getSqlSession(){
		sqlSession = threadLocal.get();
		if(sqlSession == null){
			sqlSession = sqlSessionFactory.openSession();
			threadLocal.set(sqlSession);
		}
		return sqlSession;
	}
	
	public static void closeSqlSession(){
		sqlSession = threadLocal.get();
		if(null != sqlSession){
			sqlSession.close();
			System.out.println("filter sqlSession close.");
		}
		threadLocal.set(null);
	}
	
}
